<template>
  <div class="settings-container">
    <van-nav-bar title="隐私设置" left-arrow @click-left="goBack" />
    
    <div class="content">
      <!-- 隐私概览 -->
      <div class="privacy-overview">
        <van-circle
          v-model:current-rate="encryptionRate"
          :rate="100"
          :speed="100"
          :text="encryptionRate + '%'"
          size="80px"
          layer-color="#ebedf0"
          color="linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
        />
        <div class="overview-text">
          <h3>数据加密状态</h3>
          <p>{{ encryptionRate }}% 的数据已加密保护</p>
        </div>
      </div>

      <!-- 数据分类权限设置 -->
      <div class="data-categories">
        <van-cell-group title="数据权限管理">
          <van-cell
            v-for="category in dataCategories"
            :key="category.key"
            :title="category.name"
            :label="category.description"
            center
          >
            <template #value>
              <van-stepper
                v-model="category.level"
                :min="0"
                :max="3"
                :step="1"
                integer
                @change="updatePrivacyLevel(category)"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 权限等级说明 -->
      <div class="privacy-levels">
        <van-cell-group title="权限等级说明">
          <div class="level-explanation">
            <div class="level-item">
              <van-tag type="danger">0级 - 绝密</van-tag>
              <span class="level-desc">仅本地存储，不上传云端</span>
            </div>
            <div class="level-item">
              <van-tag type="warning">1级 - 私密</van-tag>
              <span class="level-desc">需要密码/指纹验证</span>
            </div>
            <div class="level-item">
              <van-tag type="primary">2级 - 好友可见</van-tag>
              <span class="level-desc">好友可以查看</span>
            </div>
            <div class="level-item">
              <van-tag type="success">3级 - 公开</van-tag>
              <span class="level-desc">所有人可见</span>
            </div>
          </div>
        </van-cell-group>
      </div>

      <!-- 安全设置 -->
      <div class="security-settings">
        <van-cell-group title="安全设置">
          <van-cell title="生物识别" value="已开启">
            <template #icon>
              <van-icon name="shield-o" size="20" style="margin-right: 8px;" />
            </template>
          </van-cell>
          <van-cell title="数据加密" :value="encryptionEnabled ? '已开启' : '已关闭'">
            <template #icon>
              <van-icon name="lock" size="20" style="margin-right: 8px;" />
            </template>
            <template #value>
              <van-switch v-model="encryptionEnabled" @change="toggleEncryption" />
            </template>
          </van-cell>
          <van-cell title="自动锁定" value="5分钟" @click="showLockTimePicker = true">
            <template #icon>
              <van-icon name="clock-o" size="20" style="margin-right: 8px;" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 数据管理 -->
      <div class="data-management">
        <van-cell-group title="数据管理">
          <van-cell title="数据导出" @click="exportData" is-link>
            <template #icon>
              <van-icon name="down" size="20" style="margin-right: 8px;" />
            </template>
          </van-cell>
          <van-cell title="数据删除" @click="showDeleteConfirm = true" is-link>
            <template #icon>
              <van-icon name="delete-o" size="20" style="margin-right: 8px; color: #ee0a24;" />
            </template>
          </van-cell>
          <van-cell title="隐私政策" @click="showPrivacyPolicy = true" is-link>
            <template #icon>
              <van-icon name="info-o" size="20" style="margin-right: 8px;" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 敏感操作验证 -->
      <div class="sensitive-operations">
        <van-cell-group title="敏感操作验证">
          <van-cell title="查看生理周期历史" center>
            <template #value>
              <van-switch v-model="requireAuthForPeriod" @change="updateAuthSetting" />
            </template>
          </van-cell>
          <van-cell title="导出个人数据" center>
            <template #value>
              <van-switch v-model="requireAuthForExport" @change="updateAuthSetting" />
            </template>
          </van-cell>
          <van-cell title="删除账户数据" center>
            <template #value>
              <van-switch v-model="requireAuthForDelete" @change="updateAuthSetting" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </div>

    <!-- 自动锁定时间选择器 -->
    <van-popup v-model:show="showLockTimePicker" position="bottom">
      <van-picker
        :columns="lockTimeOptions"
        @confirm="onLockTimeConfirm"
        @cancel="showLockTimePicker = false"
      />
    </van-popup>

    <!-- 数据删除确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteConfirm"
      title="确认删除数据"
      message="此操作将永久删除您的所有数据，包括生理周期记录、习惯打卡记录、护肤记录等。此操作不可恢复，请谨慎操作。"
      show-cancel-button
      confirm-button-text="确认删除"
      confirm-button-color="#ee0a24"
      @confirm="deleteAllData"
    >
      <van-field
        v-model="deleteConfirmText"
        placeholder="请输入 '确认删除' 以继续"
        style="margin-top: 16px;"
      />
    </van-dialog>

    <!-- 隐私政策弹窗 -->
    <van-dialog
      v-model:show="showPrivacyPolicy"
      title="隐私政策"
      show-cancel-button
      confirm-button-text="我已了解"
      :close-on-click-overlay="false"
    >
      <div class="privacy-policy-content">
        <p>我们非常重视您的隐私和数据安全：</p>
        <ul>
          <li>所有健康数据默认本地加密存储</li>
          <li>未经您的明确同意，数据不会上传至云端</li>
          <li>您可以随时导出或删除您的个人数据</li>
          <li>敏感操作需要生物识别验证</li>
          <li>我们不会将您的数据分享给第三方</li>
        </ul>
        <p>我们承诺用最严格的标准保护您的隐私。</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { privacyApi } from '@/api/services'
import { initMqttClient, subscribeTopic, unsubscribeTopic, publishMessage } from '@/api/mqtt'

const router = useRouter()

// 基础数据
const encryptionRate = ref(98)
const encryptionEnabled = ref(true)
const showLockTimePicker = ref(false)
const showDeleteConfirm = ref(false)
const showPrivacyPolicy = ref(false)
const deleteConfirmText = ref('')
const loading = ref(false)
const userId = ref(localStorage.getItem('userId') || '00000000-0000-0000-0000-000000000000')

// 验证设置
const requireAuthForPeriod = ref(true)
const requireAuthForExport = ref(true)
const requireAuthForDelete = ref(true)

// 数据分类
const dataCategories = ref([
  {
    key: 'period',
    name: '生理周期数据',
    description: '经期、症状、情绪等记录',
    level: 0
  },
  {
    key: 'habits',
    name: '习惯打卡数据',
    description: '日常习惯打卡记录',
    level: 1
  },
  {
    key: 'skincare',
    name: '护肤记录数据',
    description: '护肤步骤、产品使用记录',
    level: 1
  },
  {
    key: 'diary',
    name: '个人日记数据',
    description: '心情日记、护肤感受等',
    level: 0
  },
  {
    key: 'profile',
    name: '个人资料数据',
    description: '昵称、头像等基本信息',
    level: 2
  }
])

// 选项数据
const lockTimeOptions = [
  '立即', '1分钟', '5分钟', '15分钟', '30分钟', '1小时', '永不'
]

// 计算属性
const overallPrivacyLevel = computed(() => {
  const total = dataCategories.value.reduce((sum, cat) => sum + cat.level, 0)
  const maxTotal = dataCategories.value.length * 3
  return Math.round((total / maxTotal) * 100)
})

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 获取用户隐私设置
    const privacyResponse = await privacyApi.getPrivacyByUserId(userId.value)
    if (privacyResponse && privacyResponse.length > 0) {
      const privacySettings = privacyResponse[0]
      
      // 更新隐私设置
      if (privacySettings.encryptionEnabled !== undefined) encryptionEnabled.value = privacySettings.encryptionEnabled
      if (privacySettings.requireAuthForPeriod !== undefined) requireAuthForPeriod.value = privacySettings.requireAuthForPeriod
      if (privacySettings.requireAuthForExport !== undefined) requireAuthForExport.value = privacySettings.requireAuthForExport
      if (privacySettings.requireAuthForDelete !== undefined) requireAuthForDelete.value = privacySettings.requireAuthForDelete
      
      // 更新数据分类权限
      if (privacySettings.dataCategories) {
        dataCategories.value.forEach(category => {
          const savedCategory = privacySettings.dataCategories.find(c => c.key === category.key)
          if (savedCategory) {
            category.level = savedCategory.level
          }
        })
      }
      
      // 更新加密率
      updateEncryptionRate()
    }
  } catch (error) {
    console.error('获取隐私设置失败:', error)
  } finally {
    loading.value = false
  }
}

// MQTT消息处理
const handleMqttMessage = (message) => {
  console.log('收到MQTT消息:', message)
  if (message.type === 'privacy_update') {
    // 更新隐私设置
    if (message.encryptionEnabled !== undefined) encryptionEnabled.value = message.encryptionEnabled
    if (message.requireAuthForPeriod !== undefined) requireAuthForPeriod.value = message.requireAuthForPeriod
    if (message.requireAuthForExport !== undefined) requireAuthForExport.value = message.requireAuthForExport
    if (message.requireAuthForDelete !== undefined) requireAuthForDelete.value = message.requireAuthForDelete
    
    // 更新数据分类权限
    if (message.dataCategories) {
      dataCategories.value.forEach(category => {
        const updatedCategory = message.dataCategories.find(c => c.key === category.key)
        if (updatedCategory) {
          category.level = updatedCategory.level
        }
      })
    }
    
    // 更新加密率
    updateEncryptionRate()
  }
}

// 初始化MQTT
const initMqtt = async () => {
  try {
    await initMqttClient()
    // 订阅用户专属主题
    subscribeTopic(`shelife/user/${userId.value}/privacy_update`, handleMqttMessage)
  } catch (error) {
    console.error('MQTT初始化失败:', error)
  }
}

// 方法
const goBack = () => {
  router.back()
}

const updatePrivacyLevel = async (category) => {
  console.log(`更新 ${category.name} 的隐私级别为: ${category.level}`)
  
  try {
    // 保存隐私设置
    await savePrivacySettings()
    showToast('隐私级别已更新')
    updateEncryptionRate()
  } catch (error) {
    console.error('更新隐私级别失败:', error)
    showToast('更新失败，请重试')
  }
}

const toggleEncryption = async (value) => {
  console.log(`数据加密: ${value ? '开启' : '关闭'}`)
  
  try {
    // 保存隐私设置
    await savePrivacySettings()
    showToast(`数据加密已${value ? '开启' : '关闭'}`)
    updateEncryptionRate()
  } catch (error) {
    console.error('切换加密状态失败:', error)
    showToast('操作失败，请重试')
  }
}

const onLockTimeConfirm = (value) => {
  console.log(`自动锁定时间设置为: ${value}`)
  showLockTimePicker.value = false
  showToast(`自动锁定时间已设置为${value}`)
}

const exportData = async () => {
  if (requireAuthForExport.value) {
    // 需要生物识别验证
    console.log('需要验证才能导出数据')
    showToast('需要验证才能导出数据')
    return
  }
  
  try {
    // 调用API导出数据
    const exportResult = await privacyApi.exportUserData(userId.value)
    
    // 创建下载链接
    const blob = new Blob([JSON.stringify(exportResult, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `shelife_data_export_${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    showToast('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    showToast('导出失败，请重试')
  }
}

const deleteAllData = async () => {
  if (deleteConfirmText.value !== '确认删除') {
    showToast('请输入正确的确认文本')
    return
  }
  
  if (requireAuthForDelete.value) {
    // 需要生物识别验证
    console.log('需要验证才能删除数据')
    showToast('需要验证才能删除数据')
    return
  }
  
  try {
    // 调用API删除数据
    await privacyApi.deleteUserData(userId.value)
    
    // 清除本地存储
    localStorage.clear()
    
    showToast('所有数据已删除')
    deleteConfirmText.value = ''
    
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('删除数据失败:', error)
    showToast('删除失败，请重试')
  }
}

const updateAuthSetting = async () => {
  console.log('更新验证设置')
  
  try {
    // 保存隐私设置
    await savePrivacySettings()
    showToast('验证设置已更新')
  } catch (error) {
    console.error('更新验证设置失败:', error)
    showToast('更新失败，请重试')
  }
}

const updateEncryptionRate = () => {
  // 根据隐私设置计算加密率
  const highPrivacyCount = dataCategories.value.filter(cat => cat.level <= 1).length
  encryptionRate.value = Math.round((highPrivacyCount / dataCategories.value.length) * 100)
}

// 保存隐私设置
const savePrivacySettings = async () => {
  // 准备保存的数据
  const privacyData = {
    userId: userId.value,
    encryptionEnabled: encryptionEnabled.value,
    requireAuthForPeriod: requireAuthForPeriod.value,
    requireAuthForExport: requireAuthForExport.value,
    requireAuthForDelete: requireAuthForDelete.value,
    dataCategories: dataCategories.value.map(category => ({
      key: category.key,
      name: category.name,
      description: category.description,
      level: category.level
    }))
  }
  
  // 调用API保存隐私设置
  const savedPrivacy = await privacyApi.createPrivacy(privacyData)
  
  // 发布MQTT消息
  publishMessage(`shelife/user/${userId.value}/privacy_update`, {
    type: 'privacy_update',
    encryptionEnabled: encryptionEnabled.value,
    requireAuthForPeriod: requireAuthForPeriod.value,
    requireAuthForExport: requireAuthForExport.value,
    requireAuthForDelete: requireAuthForDelete.value,
    dataCategories: dataCategories.value.map(category => ({
      key: category.key,
      level: category.level
    })),
    timestamp: new Date().toISOString()
  })
  
  return savedPrivacy
}

// 生命周期钩子
onMounted(() => {
  initData()
  initMqtt()
})

onUnmounted(() => {
  // 清理MQTT订阅
  unsubscribeTopic(`shelife/user/${userId.value}/privacy_update`, handleMqttMessage)
})
</script>

<style scoped lang="scss">
.settings-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

.content {
  padding: 0 16px;
}

.privacy-overview {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.overview-text {
  h3 {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #333;
  }
  
  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.data-categories,
.privacy-levels,
.security-settings,
.data-management,
.sensitive-operations {
  margin-bottom: 16px;
}

.level-explanation {
  padding: 16px;
  background: white;
}

.level-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.level-desc {
  margin-left: 12px;
  font-size: 14px;
  color: #666;
}

.privacy-policy-content {
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
  
  p {
    margin: 0 0 12px 0;
    color: #333;
    line-height: 1.5;
  }
  
  ul {
    margin: 0 0 12px 0;
    padding-left: 20px;
  }
  
  li {
    margin-bottom: 8px;
    color: #666;
    line-height: 1.5;
  }
}
</style>